﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NaviCar.Servico.Entidades;
using NaviCar.Models;
using NaviCar.DB;
using System.Web.Security;
using System.Collections.Specialized;

namespace NaviCar.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult LogOff(string ReturnUrl)
        {
            FormsAuthentication.SignOut();
            string redirectUrl = FormsAuthentication.DefaultUrl.Remove(0, 1);
            return Redirect(redirectUrl); 
        }

        [HttpPost]
        public ActionResult Login(string ReturnUrl)
        {
            
            try
            {
                LoginPessoa login = new LoginPessoa();
                TryUpdateModel<LoginPessoa>(login);
                Pessoa usuario = null;
                

                if (ModelState.IsValid)
                {
                    login.Senha = FormsAuthentication.HashPasswordForStoringInConfigFile(login.Senha, "SHA1");

                    ServicoPessoa servico = new ServicoPessoa();

                    usuario = servico.LoginRecuperarPessoa(login.Login, login.Senha);  
                }

                if (usuario != null)
                {
                    string userData = String.Empty;
                    userData = usuario.CodigoPessoa.ToString();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usuario.Nome, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

                    Response.Cookies.Add(faCookie);
                                  
                    string redirectUrl = FormsAuthentication.GetRedirectUrl(usuario.Nome, false).Remove(0,1);
                    return Redirect(redirectUrl); 
                    
                }

                return View("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View("Index");
            }

        }

       
        [Authorize()]
        public ActionResult Principal()
        {
            return View();
        }
    }
}
